package com.liurong.netty.v2.client;

import java.util.concurrent.TimeUnit;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

public class ChatClient {
	private String host;
	private int port;

	// 最好指定线程的大小。不然默认就是处理器的两倍。如果在一个应用程序中，合理分配线程大小将提供处理速度。
	private EventLoopGroup workerGroup = new NioEventLoopGroup(5);

	private ChannelFuture channelFuture = null;

	private Bootstrap bootstrap = null;

	private Channel channel = null;

	public ChatClient(String host, int port) {
		super();
		this.host = host;
		this.port = port;
	}

	public Channel getChannel() {
		return channel;
	}

	public void run() throws Exception {
		try {
			bootstrap = new Bootstrap();
			// 设置工作线程
			bootstrap.group(workerGroup);
			// 设置信道模式
			bootstrap.channel(NioSocketChannel.class);
			// 设置处理模式
			bootstrap.handler(new ChatClientInitializer(this));

			this.connect();

			// int i = 0;
			// while (true) {
			// channel.writeAndFlush("消息" + i++ + "\r\n");
			// TimeUnit.SECONDS.sleep(5);
			// }

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 有重连机制，不要将工作线程关闭。如果要关闭，在尝试建立新连接时要重新new工作线程
			// workerGroup.shutdownGracefully();
		}
	}

	public void connect() {
		// 异步建立连接
		channelFuture = bootstrap.connect(host, port).addListener(new ChannelFutureListener() {
			public void operationComplete(ChannelFuture future) throws Exception {
				if (future.isSuccess()) {
					System.out.println("连接成功！");
				} else {
					System.out.println("连接失败！等待5秒重连！");
					future.channel().eventLoop().schedule(new Runnable() {
						public void run() {
							connect();
						}
					}, 5, TimeUnit.SECONDS);
				}
			}
		});
		channel = channelFuture.channel();
	}

	public static void main(String[] args) {
		ChatClient chatClient = new ChatClient("127.0.0.1", 8888);

		try {
			chatClient.run();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
